package com.zoulj.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class KafkaConsumerListener {


    /**
     * 默认kafka是一条一条数据监听的
     * 若想要一次消费一个批量,则需要定义batchFactory
     * 下面是监听批量的写法
     * @param records
     * @param ack
     */
    @KafkaListener(topics = "topicA",containerFactory = "batchFactory")
    public void onMessage(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
        log.info("消费者接收到消息为:{}",records.toArray());
        try {
            //业务操作
        } catch (Exception ex) {
            log.error("消费数据出错 ", ex.getStackTrace());
        }finally {
            //批量手动提交数据
            ack.acknowledge();
        }
    }

    @KafkaListener(topics = "test",containerFactory = "batchFactory")
    public void onMessage2(List<String> records, Acknowledgment ack) {
        log.info("消费者接收到消息为:{}",records);
        try {
            //业务操作
        } catch (Exception ex) {
            log.error("消费数据出错 ", ex.getStackTrace());
        }finally {
            //批量手动提交数据
            ack.acknowledge();
        }
    }

}